<?php
namespace app\admin\model;

use think\Loader;
use think\Model;
use think\Validate;

class Admin extends Model
{
    //设置当前模型对应的完整数据表名称
    protected $table = 'tp_admin';


    /**
     * 登录验证处理
     */
    public function login($data){

        //验证表单数据
        $validate = Loader::validate('Admin');

        if(!$validate->check($data)){
            //返回错误提示
            return ['valid'=>0,'msg'=>$validate->getError()];
        }

        //对比数据
        $user_info = $this->where(array('username'=>$data['username'],'pwd'=>md5($data['password'])))->find();

        if(!$user_info){
            return ['valid'=>0,'msg'=>'用户名或密码错误'];
        }
        //登录成功存入session
        session('admin',$user_info);
        return ['valid'=>1,'msg'=>'登录成功'];

    }

    /**
     * 修改密码
     */
    public function pass($data){

        //自动验证器
        $validate = new Validate([
            'password'          => 'require',
            'new_password'      => 'require',
            'confirm_password'  => 'require|confirm:new_password',
        ],[
            'password.require'         => '请输入原始密码',
            'new_password.require'     => '请输入新密码',
            'confirm_password.require' => '请输入确认密码',
            'confirm_password.confirm' => '确认密码跟新密码不一致',
        ]);
        if (!$validate->check($data)) {
            return ['valid'=>0,'msg'=>$validate->getError()];
        }

        //匹配原始密码
        $user_info = $this->where(array('pwd'=>md5($data['password'])))->find();
        //判断原始密码是否正确
        if($user_info){
            $this->save(['pwd' => md5($data['new_password'])],['id' => $user_info['id']]);
            return ['valid'=>1,'msg'=>'密码修改成功'];
        }else{

            return ['valid'=>0,'msg'=>'原始密码不正确'];
        }

    }
}